/*
 * Class: StateController
 * Created by: Mary Joy Pascual
 * Date Created: 06/16/2014
 * Company: Netsuite
*/
package com.netsuite.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.netsuite.constants.ConstantsState;
import com.netsuite.dao.StateDAO;
import com.netsuite.helper.CountryHelper;
import com.netsuite.helper.ErrorHelper;
import com.netsuite.logger.LoggerImp;
import com.netsuite.migration.CSV;
import com.netsuite.migration.CSVContent;
import com.netsuite.pojo.StatePOJO;

public class StateController {
	
	private static String CLASS_NAME = StateController.class.getName();
	
	private StateDAO stateDAO = null;
	
	public StateController() throws ErrorHelper{
		stateDAO = new StateDAO();
	} 
	
	public List<String> getFieldNames() {
		
		LoggerImp.startLog(CLASS_NAME, "getFieldNames()");
		
		List <String> stateFieldList = new ArrayList<String>();
		stateFieldList.add(ConstantsState.COUNTRY);
		stateFieldList.add(ConstantsState.FULL_NAME);
		stateFieldList.add(ConstantsState.SHORT_NAME);
		stateFieldList.add(ConstantsState.ID);
		
		LoggerImp.startLog(CLASS_NAME, "getFieldNames()");
		
		return stateFieldList;
	}
	
	@SuppressWarnings("rawtypes")
	public String upsertRecord(Map<String, String> titleMap, CSV csv) throws ErrorHelper{
		
		LoggerImp.startLog(CLASS_NAME, "upsertRecord()");
		
		String message = "";

		int addedCt = 0;
		int updatedCt = 0;
		int errorCt = 0;
		int lineNo = 0;
		String error = "";
		
		try {
			
			List<StatePOJO> stateList = stateDAO.getAllStates();
			
			for (CSVContent csvContent : csv.getCsvContents()){
				lineNo++;
				StatePOJO statePojo = new StatePOJO();
				Iterator it = titleMap.entrySet().iterator();
			    while (it.hasNext()) {
			    	 Map.Entry pairs = (Map.Entry)it.next();
			    	 int index = csv.getCsvTitle().indexOf(pairs.getValue());
			    	 String content =  csvContent.getCsvContents().get(index);
			    	 if(pairs.getKey().equals(ConstantsState.ID)){
			    		 statePojo.setInternalId(content);
			    	 }
			    	 if(pairs.getKey().equals(ConstantsState.COUNTRY.toString())){
			    		 statePojo.setCountry(content);
			    	 }
			    	 if(pairs.getKey().equals(ConstantsState.FULL_NAME)){
			    		 statePojo.setStateName(content);  
			    	 }
			    	 if(pairs.getKey().equals(ConstantsState.SHORT_NAME)){
			    		 statePojo.setShortName(content);     
			    	 }
			    }
			    
			
			    if(((statePojo.getCountry().equalsIgnoreCase(null) || statePojo.getCountry().length() == 0 ) 
			     || (statePojo.getStateName().equalsIgnoreCase(null) || statePojo.getStateName().length() == 0) || !isCountryValid(statePojo))){
			    	error = error +"---> Err CSV Line #"+String.valueOf(lineNo)+"\n";
			    	errorCt++;
			    } else {
			    	String internalId = isStateExisting(stateList, statePojo);
			    	if(internalId.equalsIgnoreCase("")){
				    	stateDAO.addState(statePojo);
				    	stateList.add(statePojo);
				    	addedCt++;
				    } else {
				    	statePojo.setInternalId(internalId);
				    	stateDAO.updateState(statePojo);
				    	updatedCt++;
				    }
			    }
		    }
			
			
			message = "\nTotal No. of Records: "+ csv.getCsvContents().size() + "\n" +
					  "Added  : "+ String.valueOf(addedCt)   + " Record/s\n" +
					  "Updated: "+ String.valueOf(updatedCt) + " Record/s\n" +
					  "Error  : "+ String.valueOf(errorCt)   + " Record/s\n" +
					  error;	  
			
			LoggerImp.infoLog(CLASS_NAME, message);
					
		} catch (Exception e){
			throw new ErrorHelper(CLASS_NAME, e.getMessage());
		}
		
		LoggerImp.endLog(CLASS_NAME, "upsertRecord()");
		
	    return message;
	}
	
	private String isStateExisting(List<StatePOJO> stateList, StatePOJO statePOJO){
		
		LoggerImp.startLog(CLASS_NAME, "isStateExisting()");
		
		String internalId = "";
		for(StatePOJO state: stateList){
			if(CountryHelper.countryFromString(statePOJO.getCountry()).toString().equalsIgnoreCase(state.getCountry()) && statePOJO.getStateName().endsWith(state.getStateName())){
				internalId = state.getInternalId();
			} else if (statePOJO.getShortName() != null){
				if(CountryHelper.countryFromString(statePOJO.getCountry()).toString().equalsIgnoreCase(state.getCountry()) && statePOJO.getShortName().equalsIgnoreCase(state.getShortName())){
					internalId = state.getInternalId();
				}
			}
		}
	
		LoggerImp.endLog(CLASS_NAME, "isStateExisting()");
		
		return internalId;
	}
	
	private boolean isCountryValid(StatePOJO statePOJO){
		
		LoggerImp.startLog(CLASS_NAME, "isCountryValid()");
		
		if(CountryHelper.countryFromString(statePOJO.getCountry()) == null){
			return false;
		} 
		
		LoggerImp.endLog(CLASS_NAME, "isStateExisting()");
		
		return true;
	}
	
	
}
